package cn.westv.scps.web.controller.base;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.westv.scps.utils.StringUtils;


public class DateEditor extends PropertyEditorSupport
{
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final DateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private DateFormat              dateFormat;
    private boolean                 allowEmpty  = true;

    public DateFormat getDateFormat()
    {
        return dateFormat;
    }

    public void setDateFormat(DateFormat dateFormat)
    {
        this.dateFormat = dateFormat;
    }

    public boolean isAllowEmpty()
    {
        return allowEmpty;
    }

    public void setAllowEmpty(boolean allowEmpty)
    {
        this.allowEmpty = allowEmpty;
    }

    public DateEditor(DateFormat dateFormat, boolean allowEmpty)
    {
        super();
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
    }

    public DateEditor(DateFormat dateFormat)
    {
        super();
        this.dateFormat = dateFormat;
    }

    public DateEditor()
    {
        super();
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException
    {
        if (StringUtils.isBlank(text))
        {
            setValue(null);
            return;
        }
        if (this.allowEmpty && !org.springframework.util.StringUtils.hasText(text))
        {
            setValue(null);
        } else
        {
            try
            {
                if (dateFormat != null)
                {
                    setValue(this.dateFormat.parse(text));
                } else
                {
                    if (text.contains(":"))
                    {
                        setValue(TIME_FORMAT.parse(text));
                    } else
                    {
                        setValue(DATE_FORMAT.parse(text));
                    }
                }

            } catch (ParseException ex)
            {
                throw new IllegalArgumentException("Could not parse date:" + ex.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception
    {
        System.out.println(TIME_FORMAT.parse("2014-06-27 23:59:59"));
    }

    @Override
    public String getAsText()
    {
        Date value = (Date) getValue();
        DateFormat dateFormat = this.dateFormat;
        if (dateFormat == null)
        {
            dateFormat = TIME_FORMAT;
        }
        return (value != null ? dateFormat.format(value) : "");
    }
}
